<template>
  <view v-if="isUploadFinish">
    <view :class="[`${prefixCls}-question-container`]" v-if="!isFinish || isDetail">
      <cu-navbar :navPlaceholder="true" navBgColor="rgba(255,255,255,1)" :showHome="false" :showBack="false"> </cu-navbar>
      <view class="question-title">{{ questionDeatil.name }}</view>
      <view class="question-text"> {{ questionDeatil.remark }} </view>
      <view class="question-box">
        <view v-for="(item, index) in questionList" :key="index" :class="item.submitRequired ? 'required_box' : ''">
          <view :id="`question${index}`" class="question-item" v-if="item.type == '填空题'" :ref="`question${index}`">
            <view class="question-item-title"><text style="color: red" v-if="item.is_required">*</text>{{ index + 1 }}、{{ item.title }}</view>
            <uv-textarea v-model="questionForm[`question${index}`]" type="textarea" height="100" :disabled="isDetail" :count="true"></uv-textarea>
          </view>

          <view :id="`question${index}`" class="question-item" v-if="item.type == '多选题'" :ref="`question${index}`">
            <view class="question-item-title"><text style="color: red" v-if="item.is_required">*</text>{{ index + 1 }}、{{ item.title }}</view>
            <uv-checkbox-group :active-color="theme" v-model="questionForm[`question${index}`]" :disabled="isDetail">
              <uv-checkbox :name="it.option" v-for="(it, idx) in item.options" :key="idx"> {{ it.option }} </uv-checkbox>
            </uv-checkbox-group>
          </view>
          <view :id="`question${index}`" class="question-item" v-if="item.type == '单选题'" :ref="`question${index}`">
            <view class="question-item-title"><text style="color: red" v-if="item.is_required">*</text>{{ index + 1 }}、{{ item.title }}</view>
            <uv-radio-group v-model="questionForm[`question${index}`]" :name="it.option" v-for="(it, idx) in item.options" :key="idx" :active-color="theme" :disabled="isDetail">
              <uv-radio :name="it.option"> {{ it.option }} </uv-radio>
            </uv-radio-group>
          </view>
          <view :id="`question${index}`" class="question-item" v-if="item.type == '打分题'" :ref="`question${index}`">
            <view class="question-item-title"><text style="color: red" v-if="item.is_required">*</text>{{ index + 1 }}、{{ item.title }}</view>
            <view class="score-line">
              <view
                class="score-line-item"
                :class="it == questionForm[`question${index}`] ? 'active-score' : isDetail ? 'disable-score-line-item' : ''"
                v-for="(it, idx) in 5"
                :key="idx"
                @click="setScort(it, index)"
              >
                {{ it }}
              </view>
            </view>
          </view>
          <view :id="`question${index}`" class="question-item" v-if="item.type == '排序题'" :ref="`question${index}`">
            <view class="question-item-title"><text style="color: red" v-if="item.is_required">*</text>{{ index + 1 }}、{{ item.title }}</view>
            <view class="sort-box">
              <view class="sort-line" v-for="(it, idx) in item.options" :key="idx" @click="setSort(it.option, index)">
                <view class="sort-line-box" :class="isDetail ? 'disable-sort-line-box' : ''">{{
                  questionForm[`question${index}`].indexOf(it.option) > -1 ? questionForm[`question${index}`].indexOf(it.option) + 1 : ''
                }}</view>
                <view class="sore-line-text">{{ it.option }}</view>
              </view>
            </view>
          </view>
        </view>
        <view class="question-btn" v-if="!isDetail">
          <uv-button type="primary" @click="submit" class="submit-btn">提交</uv-button>
        </view>
      </view>
      <uv-safe-bottom></uv-safe-bottom>
    </view>
    <view :class="[`${prefixCls}-question-container`]" v-else>
      <cu-navbar :navPlaceholder="true" navBgColor="rgba(255,255,255,1)" :showHome="false" :showBack="false"> </cu-navbar>
      <view class="question-ok-container">
        <view class="question-ok-box"><uv-icon name="checkbox-mark" color="#ffffff" size="60"></uv-icon></view>
        <view class="question-ok-title">您的问卷已经提交，感谢您的参与！</view>
      </view></view
    >
  </view>
  <uv-modal ref="noQuestionModal" title="提示" content="您没权限参与此次问卷调查" :showConfirmButton="false" :closeOnClickOverlay="false" align="center"></uv-modal>
</template>

<script>
import $platform from '@/common/platform'
import ROUTE from '@/router'
import { mapActions, mapGetters } from 'vuex'
import { checkQuestionAuth, getFormScene, getQuestionDetail, submitQuestion } from './api'
export default {
  name: 'questionDetail',
  components: {},
  mixins: [],
  props: {},
  data() {
    return {
      questionForm: {},
      questionId: '',
      questionList: [],
      isFinish: false,
      isDetail: false,
      questionDeatil: {},
      is_rented_user: false,
      isUploadFinish: false,
    }
  },
  // 侦听属性
  watch: {},
  // 计算属性
  computed: {
    ...mapGetters(['theme', 'userInfo', 'isLogin']),
  },

  async onLoad(options) {
    if (options.id) {
      this.questionId = options.id
    }
    if (options.scene) {
      await this.getFormScene(options.scene)
    }

    this.isDetail = options.isDetail == 1 ? true : false
    await this.getQuestionList()
  },
  // 监听页面初次渲染完成，此时组件已挂载完成
  onReady() {},
  // 下拉刷新
  onPullDownRefresh() {},
  // 加载更多
  onReachBottom() {},
  methods: {
    ...mapActions([]),
    //通过scene获取题目id
    async getFormScene(sceneId) {
      const data = await getFormScene({ scene: sceneId })
      if (data.errcode == 0) {
        this.questionId = data.data.id
      }
    },
    setScort(item, index) {
      if (this.isDetail) return
      this.questionForm[`question${index}`] = item
    },
    setSort(item, index) {
      if (this.isDetail) return
      if (this.questionForm[`question${index}`].includes(item)) {
        let spliceIndex = this.questionForm[`question${index}`].indexOf(item)
        this.questionForm[`question${index}`].splice(spliceIndex, 1)
      } else {
        this.questionForm[`question${index}`].push(item)
      }
    },
    async getQuestionList() {
      try {
        const data = await getQuestionDetail({ type: 1, id: this.questionId, user_id: this.userInfo.user_id ? this.userInfo.user_id : '' })
        // this.dataList = [{ name: '测试问卷2测试问卷2测试问卷2测试问卷2测试问卷2测试问卷2', status: 1 }]
        //status为1是已提交，0是未提交
        if (data.user_limit != 0 && !this.isLogin) {
          uni.showModal({
            title: '提示',
            content: '系统检测到您尚未登录，请登录后继续操作！',
            showCancel: false,
            success: (res) => {
              if (res.confirm) {
                ROUTE.redirect('/pages/user/auth', { redirect: encodeURIComponent(getCurrentPages().pop().$page.fullPath) })
              }
            },
          })
          return
        }

        // //请求接口判断是不是在租租户 is_rented_user
        // //user_limit为1，且是在租用户才能答题
        // if (data.user_limit == 1 && !this.is_rented_user) {
        //   this.$refs.noQuestionModal.open()
        //   return
        // }
        // //user_limit为2，且不是在租用户才能答题
        // if (data.user_limit == 2 && this.is_rented_user) {
        //   this.$refs.noQuestionModal.open()
        //   return
        // }
        this.questionId = data.id
        //调用接口判断该租户是否有权限
        const res = await checkQuestionAuth({ id: this.questionId, user_id: this.userInfo.user_id || '' })
        if (res.data) {
        } else {
          this.$refs.noQuestionModal.open()
          return
        }
        this.questionList = data.topic
        this.questionDeatil = data
        this.isFinish = data.userAnswer == null ? false : true
        this.questionList.forEach((item, index) => {
          let formIndex = 'question' + index
          if (item.type == '多选题' || item.type == '排序题') {
            this.questionForm[formIndex] = []
          } else {
            this.questionForm[formIndex] = ''
          }
        })
        if (this.isFinish && this.isDetail) {
          data.userAnswer.answer.forEach((item, index) => {
            let formIndex = 'question' + index
            if (item.type == '多选题' || item.type == '排序题') {
              this.questionForm[formIndex] = item.answerList.map((it) => it.answer)
            } else {
              this.questionForm[formIndex] = item.answerList[0].answer
            }
          })
        }
        this.isUploadFinish = true
      } catch (e) {}
    },
    // 校验必填
    checkRequired() {
      let needRequired = 0
      this.questionList.forEach((item, index) => {
        if (item.is_required) {
          if (item.type == '多选题') {
            if (this.questionForm[`question${index}`].length == 0) {
              item.submitRequired = true
              needRequired += 1
              if (needRequired == 1) {
                uni.pageScrollTo({
                  duration: 300, // 滚动动画过渡时间
                  scrollTop: 100,
                  selector: index == 0 ? '.question-title' : `#question${index - 1}`,
                })
              }
            } else {
              item.submitRequired = false
            }
          } else if (item.type == '排序题') {
            if (this.questionForm[`question${index}`].length < item.options.length) {
              item.submitRequired = true
              needRequired += 1
              if (needRequired == 1) {
                uni.pageScrollTo({
                  duration: 300, // 滚动动画过渡时间
                  scrollTop: 100,
                  selector: index == 0 ? '.question-title' : `#question${index - 1}`,
                })
              }
            } else {
              item.submitRequired = false
            }
          } else {
            if (this.questionForm[`question${index}`] == '') {
              item.submitRequired = true
              needRequired += 1
              if (needRequired == 1) {
                uni.pageScrollTo({
                  duration: 300, // 滚动动画过渡时间
                  scrollTop: 100,
                  selector: index == 0 ? '.question-title' : `#question${index - 1}`,
                })
              }
            } else {
              item.submitRequired = false
            }
          }
        }
      })
      return needRequired == 0 ? true : false
    },
    //提交答案
    async submit() {
      if (!this.checkRequired()) {
        return false
      }
      const params = {
        questionnaire_id: this.questionId,
        user_id: this.userInfo.user_id ? this.userInfo.user_id : '',
        tel: this.userInfo.phone ? this.userInfo.phone : '',
        source: uni.getSystemInfoSync().uniPlatform,
        mac: $platform.device.deviceId,
        status: 1,
        topic: [],
      }
      this.questionList.forEach((item, index) => {
        if (item.type == '多选题' || item.type == '排序题') {
          item.answerList = this.questionForm[`question${index}`].map((it) => {
            return {
              answer: it,
            }
          })
        } else {
          item.answerList = [
            {
              answer: this.questionForm[`question${index}`],
            },
          ]
        }
      })
      params.topic = this.questionList
      params.array = [1, 2, 4, 5]
      try {
        const data = await submitQuestion(params)
        if (data.errcode == 0) {
          this.$uv.toast('提交成功')
          this.isFinish = true
        } else {
          this.$uv.toast(data.errmsg)
        }
      } catch (e) {}
    },
  },
}
</script>

<style lang="scss" scoped>
.#{prefixCls('question-container')} {
  position: relative;
  background: #f7f7f7;
  padding-top: 20rpx;
  padding: 20rpx 30rpx;
  min-height: 100vh;
  box-sizing: border-box;
  .question-title {
    text-align: center;
    padding: 0 50rpx;
    font-size: 44rpx;
    font-weight: bold;
    color: $uv-primary;
  }
  .question-text {
    margin: 10rpx 0;
    font-size: 30rpx;
    line-height: 40rpx;
    margin-bottom: 30rpx;
  }
  .question-box {
    width: 100%;
    border-top: 2rpx dashed rgb(200, 201, 204);
    .question-item {
      font-size: 30rpx;
      .question-item-title {
        margin: 30rpx 0 20rpx;
      }
      ::v-deep .uv-checkbox-group--row {
        flex-direction: column;
        margin-left: 40rpx;
        margin-bottom: 20rpx;
      }
      ::v-deep .uv-checkbox {
        margin-bottom: 30rpx;
      }
      ::v-deep .uv-radio-group--row {
        flex-direction: column;
        margin-left: 40rpx;
        margin-bottom: 20rpx;
      }
      ::v-deep .uv-radio {
        margin-bottom: 20rpx;
      }
      .score-line {
        margin-left: 40rpx;
        display: flex;
        .score-line-item {
          width: 50rpx;
          height: 50rpx;
          border-radius: 50%;
          border: 2rpx solid rgb(200, 201, 204);
          text-align: center;
          line-height: 50rpx;
          color: #000;
          margin-right: 20rpx;
        }
        .active-score {
          background-color: $uv-primary;
          color: #fff;
        }
        .disable-score-line-item {
          background-color: #ebedf0 !important;
          color: rgb(200, 201, 204);
        }
      }
      .sort-box {
        margin-left: 40rpx;
        .sort-line {
          display: flex;
          align-items: center;
          margin-bottom: 20rpx;
          .sort-line-box {
            width: 30rpx;
            height: 30rpx;
            border-radius: 4rpx;
            border: 2rpx solid rgb(200, 201, 204);
            margin-right: 20rpx;
            text-align: center;
            line-height: 30rpx;
          }
          .disable-sort-line-box {
            background-color: #ebedf0 !important;
            color: rgb(200, 201, 204);
          }
          .sore-line-text {
            font-size: 30rpx;
          }
        }
      }
    }
    .required_box {
      border: 2rpx dashed red;
    }
  }

  .question-btn {
    display: flex;
    justify-content: center;
    width: 100%;
    margin-top: 30rpx;
    .submit-btn {
      margin: 0 30rpx;
      width: 80%;
    }
  }
  .question-ok-container {
    width: 100%;
    display: flex;
    align-items: center;
    flex-direction: column;
    height: 100%;
    .question-ok-box {
      width: 150rpx;
      height: 150rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: $uv-primary;
      border-radius: 50%;
      margin-top: 200rpx;
    }
    .question-ok-title {
      text-align: center;
      margin-top: 40rpx;
      font-size: 38rpx;
    }
  }
}
</style>
